/************************************************************************
Copyright 2003, 2004, 2005, 2006, 2007, 2008 Grid Technology Research Center,
National Institute of Advanced Industrial Science and Technology.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************/

package jp.aist.gtrc.plus.scheduler.specific.sge.qbase;

import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;

import jp.aist.gtrc.plus.reserve.ReserveException;
import jp.aist.gtrc.plus.scheduler.specific.sge.jaxb.common.*;
import jp.aist.gtrc.plus.scheduler.specific.sge.status.SGENodeStatus;
import jp.aist.gtrc.plus.scheduler.specific.sge.status.SGEQueueStatus;
import jp.aist.gtrc.plus.scheduler.specific.sge.status.SGEServerStatus;
import jp.aist.gtrc.plus.scheduler.status.JobStatus;
import jp.aist.gtrc.plus.scheduler.status.NodeStatus;
import jp.aist.gtrc.plus.scheduler.status.QbaseMainServer;
import jp.aist.gtrc.plus.scheduler.status.QueueStatus;
import jp.aist.gtrc.plus.scheduler.status.ServerStatus;
import jp.aist.gtrc.plus.scheduler.sys.SchedulerException;
import jp.aist.gtrc.plus.scheduler.util.CmdUtil;
import jp.aist.gtrc.plus.scheduler.util.TextUtil;

import org.apache.log4j.Logger;

public class SGEQbaseMainServer extends QbaseMainServer {

	private static final SGEQbaseMainServer instance;
	private static final SGEJAXBObjectBuilder builder;
	private static final SGEServerStatus serverStatus;

	protected static final Logger logger = Logger.getLogger(SGEQbaseMainServer.class);

	static {

		instance = new SGEQbaseMainServer();
		builder = new SGEJAXBObjectBuilder();
		serverStatus = new SGEServerStatus(builder.createServer("dummy"));

	}

	public static SGEQbaseMainServer getInstance() {

		return instance;

	}

	private static LinkedList<String> getExecNodeNamesByQconf() throws ReserveException {

		return CmdUtil.runCommand(new String[]{"qconf", "-sel"});

	}

	private static LinkedList<String> runQhost(boolean withAttr) throws ReserveException {

		final int HEADLINE_NUM = 3;
		/*
		 * qhost output always has 3 line headers as follows:
		 * 		HOSTNAME	...
		 * 		----------  ....
		 * 		global		...
		 * They are needless, so skip them.
		 */

		String[] cmd = withAttr ? new String[]{"qhost", "-F"} : new String[]{"qhost"};
		LinkedList<String> stdout = CmdUtil.runCommand(cmd);
		for (int i = 0; i < HEADLINE_NUM; i++) {
			stdout.removeFirst();	// drop header
		}

		return stdout;

	}

	private static LinkedList<LinkedList<String>> getExecNodeInfoByQhostWithAttr() throws ReserveException {

		LinkedList<String> stdout = runQhost(true);
		LinkedList<LinkedList<String>> nodeList = new LinkedList<LinkedList<String>>();
		LinkedList<String> node = null;
		for (String line : stdout) {
			if (line.startsWith(" ") == false) {
				node = new LinkedList<String>();
				nodeList.add(node);
			}
			if (node != null) {
				node.add(line);
			}
		}

		return nodeList;

	}

	public boolean isConnected() {

		return true;

	}

	public void disconnect() {
	}

	public ServerStatus getServerStatus() throws SchedulerException {

		return serverStatus;

	}

	public Collection<NodeStatus> getNodeStatus() throws SchedulerException {

		LinkedList<NodeStatus> list = new LinkedList<NodeStatus>();

		LinkedList<String> names = getExecNodeNamesByQconf();
		LinkedList<LinkedList<String>> nodeList = getExecNodeInfoByQhostWithAttr();

		for (LinkedList<String> nodeAttrs : nodeList) {
			String hostname = names.removeFirst();
			JAXBSGENode jaxbNode = builder.createNode(hostname, nodeAttrs);
			if (jaxbNode != null) {
				SGENodeStatus node = new SGENodeStatus(jaxbNode);
				list.add(node);
			}
		}

		return list;

	}

	public Collection<QueueStatus> getQueueStatus() throws SchedulerException {

		LinkedList<QueueStatus> list = new LinkedList<QueueStatus>();

		Collection<String> stdout = CmdUtil.runCommand(new String[]{"qconf", "-sql"});
		HashMap<String, Collection<JAXBSGEQinstance>> qinsMap =
			getQInstanceMap(getQInstanceStatus());

		for (String line : stdout) {
			JAXBSGEQueue jaxbQueue = builder.createQueue(line, qinsMap);
			if (jaxbQueue != null) {
				SGEQueueStatus queue = new SGEQueueStatus(jaxbQueue);
				list.add(queue);
			}
		}

		return list;

	}

	private HashMap<String, Collection<JAXBSGEQinstance>> getQInstanceMap(
			Collection<JAXBSGEQinstance> qinsList) throws SchedulerException {

		HashMap<String, Collection<JAXBSGEQinstance>> map =
			new HashMap<String, Collection<JAXBSGEQinstance>>();

		for (JAXBSGEQinstance qins : qinsList) {
			String qname = qins.getQUQname();
			Collection<JAXBSGEQinstance> list = map.get(qname);
			if (list == null) {
				list = new LinkedList<JAXBSGEQinstance>();
				map.put(qname, list);
			}
			list.add(qins);
		}

		return map;

	}

	public Collection<JAXBSGEQinstance> getQInstanceStatus() throws SchedulerException {

		LinkedList<JAXBSGEQinstance> list = new LinkedList<JAXBSGEQinstance>();

		Collection<String> stdout = CmdUtil.runCommand(new String[]{"qstat", "-f"});
		for (String line : stdout) {
			JAXBSGEQinstance jaxbQins = builder.createQinstance(line);
			if (jaxbQins != null) {
				list.add(jaxbQins);
			}
		}

		return list;

	}

	public Collection<JobStatus> getJobStatus() throws SchedulerException {
		assert(false);
		throw new SchedulerException("NOT SUPPORTED: SGEQbaseMainServer:getJobStatus()");
	}

	public String getPENames() {

		try {
			Collection<String> stdout
				= CmdUtil.runCommand(new String[]{"qconf", "-spl"});
			return  (stdout.size() == 0) ? "NONE" : TextUtil.fromList(stdout, ",");
		} catch (ReserveException e) {
			return "NONE";
		}

	}

}
